<template>
	<div class="system-menu-container layout-pd">
		<el-card shadow="hover">
			<div class="system-menu-search mb15">
				<el-row :gutter="20">
					<el-col :span="24" v-auths="['system:dept:query']">
						<el-input size="default" placeholder="请输入部门名称" class="mt10"
							v-model="state.tableData.param.deptName" clearable @keyup.enter.native="getTableData" />
						<el-select v-model="state.tableData.param.status" placeholder="部门状态" clearable class="ml10" @change="getTableData"
							size="default">
							<el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label"
								:value="dict.value" />
						</el-select>
						<el-button size="default" type="primary" class="mt10" @click="getTableData">
							<el-icon>
								<ele-Search />
							</el-icon>
							查询
						</el-button>
						<el-button size="default" class="mt10" type="info" @click="resetParamData()">
							<el-icon>
								<ele-Refresh />
							</el-icon>
							重置
						</el-button>
					</el-col>
					<el-col :span="24">
						<el-button size="default" type="success" class="mt10" @click="onOpenAddDept('add')"
							v-auth="'system:dept:add'">
							<el-icon>
								<ele-Plus />
							</el-icon>
							新增部门
						</el-button>
						<el-button size="default" type="primary" class="mt10" :icon="'ele-Sort'" @click="handleExpandAll">
							{{ state.tableData.handleExpandAll ? '折叠' : '展开' }}
						</el-button>
					</el-col>
				</el-row>
			</div>
			<el-table v-if="refreshTable" :data="state.tableData.data" v-loading="state.tableData.loading"
				style="width: 100%" row-key="deptId" ref="tableRef" border @row-click="onTabelRowClick"
				:default-expand-all="state.tableData.handleExpandAll" :expand-row-keys="expands"
				@expand-change="expandSelect">
				:tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
				<el-table-column label="部门名称" show-overflow-tooltip width="200">
					<template #default="scope">
						<SvgIcon :name="scope.row.icon" />
						<span class="ml10">{{ scope.row.deptName }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="leader" label="负责人" show-overflow-tooltip></el-table-column>
				<el-table-column prop="orderNum" label="排序" show-overflow-tooltip></el-table-column>
				<el-table-column label="创建时间" show-overflow-tooltip>
					<template #default="scope">
						<span>{{ scope.row.createTime }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="createBy" label="创建人" show-overflow-tooltip></el-table-column>
				<el-table-column label="状态" show-overflow-tooltip width="80">
					<template #default="scope">
						<dict-tag :options="sys_normal_disable" :value="scope.row.status" />
					</template>
				</el-table-column>
				<el-table-column label="操作" show-overflow-tooltip width="140" fixed="right"
					v-auths="['system:dept:edit', 'system:dept:add', 'system:dept:remove']">
					<template #default="scope">
						<el-button size="small" text type="primary" @click="onOpenAddDept('add')"
							v-auth="'system:dept:add'">新增</el-button>
						<el-button size="small" text type="primary" @click="onOpenEditDept('edit', scope.row)"
							v-auth="'system:dept:edit'">修改</el-button>
						<el-button size="small" text type="primary" @click="onTabelRowDel(scope.row)"
							v-auth="'system:dept:remove'">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>
		<DeptDialog ref="deptDialogRef" @refresh="getTableData()" />
	</div>
</template>

<script setup lang="ts" name="systemDept">
import { defineAsyncComponent, ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useDept } from '/@/api/system/dept';
import { handleTree } from '/@/utils/tool';
import { useDict } from '/@/utils/dict';

const { sys_normal_disable } = useDict("sys_normal_disable");

// 引入组件
const DeptDialog = defineAsyncComponent(() => import('/@/views/system/dept/dialog.vue'));

// 定义变量内容
const deptDialogRef = ref();
const tableRef = ref();
const refreshTable = ref(true);
const expands = ref(<any>[]);
const state = reactive<SysDeptState>({
	tableData: {
		// 表格树数据
		data: [],
		// 部门树选项
		deptOptions: [],
		total: 0,
		loading: false,
		handleExpandAll: false,
		param: {
			pageNum: 1,
			pageSize: 10,
			deptName: '',
			status: '',
		},
	},
});

/**
 * 初始化表格数据
 * @returns
 */
const getTableData = async () => {
	state.tableData.loading = true;
	try {
		const res = await useDept().listDept(state.tableData.param);
		state.tableData.data = handleTree(res.data, 'deptId', 'parentId', 'children');
		state.tableData.total = res.data.length;
	} catch (error) {
		Promise.reject(error);
	}
	state.tableData.loading = false;
};

/**
 * 打开新增部门弹窗
 * @param type
 * @param data 部门树数据
 */
const onOpenAddDept = (type: string) => {
	deptDialogRef.value.openDialog(type, state.tableData.data);
};
/**
 * 打开编辑部门弹窗
 * @param type
 * @param row 当前行数据
 */
const onOpenEditDept = (type: string, row: DeptTreeType) => {
	deptDialogRef.value.openDialog(type, state.tableData.data, row);
};


/**
 * 删除部门
 * @param row 当前行数据
 */
const onTabelRowDel = async (row: RowDeptType) => {
	try {
		if ((row.children && row.children.length > 0)) {
			ElMessage.warning('存在下级部门，不允许删除');
			return;
		}
		await ElMessageBox.confirm(`此操作将永久删除部门：${row.deptName}, 是否继续?`, '提示', {
			confirmButtonText: '删除',
			cancelButtonText: '取消',
			type: 'warning',
		}).then(async () => {
			const response = await useDept().delDept(row.deptId);
			ElMessage.success(response.msg);
			getTableData();
		});
	} catch (error) {
		Promise.reject(error);
	}
};



/**
 * 重置查询参数
 */
const resetParamData = () => {
	state.tableData.param = {
		pageNum: 1,
		pageSize: 10,
		deptName: '',
		status: '',
	};
	getTableData();
};

/**
 * 列表行点击事件
 */
const onTabelRowClick = (row: RowDeptType) => {
	tableRef.value.toggleRowExpansion(row);
};

/**
 * 展开/收起
 * @param row 当前行数据
 * @param expanded 是否展开
 */
const expandSelect = (row: RowDeptType, expanded: boolean) => {
	if (expanded) {
		expands.value.push(row.deptId);
	} else {
		const index = expands.value.findIndex((item: number) => item === row.deptId);
		expands.value.splice(index, 1);
	}
};

/**
 * 展开全部/收起全部
 */
const handleExpandAll = () => {
	refreshTable.value = false;
	state.tableData.handleExpandAll = !state.tableData.handleExpandAll;
	nextTick(() => {
		refreshTable.value = true;
	});
};



// 页面加载时
onMounted(() => {
	getTableData();
});
</script>
<style lang="scss" scoped>
.mt10 {
	max-width: 140px;
	margin: 10px 0 10px 10px;
}
</style>